package com.sgb.member.ui.activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;

import androidx.databinding.DataBindingUtil;

import androidx.lifecycle.ViewModelProvider;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.sgb.member.MemberConfig;
import com.sgb.member.R;
import com.sgb.member.databinding.ActivityMemberRelieveApplyBinding;
import com.sgb.member.databinding.LayoutNewAddItemBinding;
import com.sgb.member.entity.ApplyCompanyBean;
import com.sgb.member.entity.CompanyDeptBean;
import com.sgb.member.entity.MemberBean;
import com.sgb.member.entity.MemberRelieveBean;

import com.sgb.member.weight.MemberCommonDialog;
import com.swgk.core.base.AppActivity;
import com.swgk.core.customview.CfkEditView;
import com.swgk.core.customview.ItemInputTextView;
import com.swgk.core.dialog.DialogHelper;
import com.swgk.core.util.DisplayUtil;
import com.swgk.core.util.MToast;
import com.swgk.core.util.SharedPreferenceUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * 会员解除
 */
public class MemberRelieveActivity extends AppActivity implements ItemInputTextView.OnWholeItemClickListener {

    private ActivityMemberRelieveApplyBinding mBinding;
    private MemberRelieveModel sModel;
    private MemberBean memberBean;
    private int mCurPos;

    private OptionsPickerView<CompanyDeptBean> mOptionDept;

    // 会员解除审批添加接口Bean类
    private MemberRelieveBean relieveBean;
    private String companyId = "";
    private List<MemberRelieveBean.ParamDtos> viewList = new ArrayList<>();//自定义参数
    private int comType;
    private String flag = "0";//有审批 1，无审批 0

    public static void start(Context context, MemberBean bean, int pos, String flag) {
        Intent intent = new Intent(context, MemberRelieveActivity.class);
        intent.putExtra("Bean", bean);
        intent.putExtra("Position", pos);
        intent.putExtra("flag", flag);
        context.startActivity(intent);
    }

    @Override
    protected boolean statusBarDark() {
        return true;
    }

    @Override
    protected void initView() {
        comType = MemberConfig.getInstance().getComType();
        Intent intent = getIntent();
        memberBean = (MemberBean) intent.getSerializableExtra("Bean");
        mCurPos = intent.getIntExtra("Position", 0);
        flag = intent.getStringExtra("flag");
        mBinding = DataBindingUtil.setContentView(this, R.layout.activity_member_relieve_apply);
        sModel = new ViewModelProvider(this).get(MemberRelieveModel.class);
        mBinding.setLifecycleOwner(this);
        mBinding.activityBar.titleView.setText("会员解除申请");
        mBinding.activityBar.ivBack.setOnClickListener(v -> finish());
        registerObserver();
    }

    @Override
    protected void init() {
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        //设置沉浸式状态栏的上移问题
        setTileImmerse(true);
        mBinding.itemInputName.setMemberStyle();
        mBinding.itemInputDepartment.setMemberStyle();
        mBinding.itemInputCompanyName.setMemberStyle();
        setCfkEditViewStyle(mBinding.cftPerformance);
        mBinding.itemInputDepartment.setOnWholeItemClickListener(this);
        mBinding.submit.setOnClickListener(this);
        initUserInfo();
        mBinding.tvAddView.setOnClickListener(v -> addView());
        if (comType == MemberConfig.WEBSITE_FOR_COMPANY) {
            mBinding.itemInputDepartment.setVisibility(View.VISIBLE);
        } else {
            mBinding.itemInputDepartment.setVisibility(View.GONE);
        }
    }

    private void initUserInfo() {
        String userName = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.REAL_NAME, "");
        String userNo = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.USER_NO, "");
        String companyName = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.COMPANY_NAME, "");
        String companyNo = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.COMPANY_NO, "");
        mBinding.itemInputName.setContent(userName);
        mBinding.itemInputCompanyName.setContent(memberBean.getCompanyName());
        relieveBean = new MemberRelieveBean();
        relieveBean.setNo(memberBean.getNo()); //no 传入申请加盟和邀请加盟列表no
        // 申请人信息
        relieveBean.setApplyUserName(userName);
        relieveBean.setApplyUserNo(userNo);
        relieveBean.setApplyCompanyName(companyName);
        relieveBean.setApplyCompanyNo(companyNo);
        relieveBean.setRelation(memberBean.getMemberUpdateLeverType());
        relieveBean.setRelieveBusinessName(memberBean.getCompanyName());
        relieveBean.setRelieveBusinessNo(memberBean.getCompanyNo());
        if(memberBean.getCheckType()==1){
            relieveBean.setRelieveType("2");//解除类型 1企业 2个人
        }else {
            relieveBean.setRelieveType("1");
        }

        sModel.getMyCompanyList();
    }

    private void setCfkEditViewStyle(CfkEditView editView) {
        editView.getEditText().setTextColor(getResources().getColor(R.color.FF000000));
        editView.getEditText().setHintTextColor(getResources().getColor(R.color.C0C4CC));
        editView.getEditText().setMinHeight(DisplayUtil.dip2px(editView.getContext(), 150));
    }

    private void registerObserver() {
        sModel.dialog.observe(this, aBoolean -> {
            if (aBoolean) {
                if (!DialogHelper.isShowing()) {
                    DialogHelper.showProgressDialog(MemberRelieveActivity.this, "数据获取中...");
                }
            } else {
                DialogHelper.dismissProgressDialog();
            }
        });
        sModel.userInfo.observe(this, aBoolean -> {
            if (aBoolean) {
                initUserInfo();
            } else {
                finish();
            }
        });
        sModel.mCompanyList.observe(this, applyCompanyBeans -> {
            if (TextUtils.isEmpty(companyId)) {
                for (ApplyCompanyBean applyCompanyBean : applyCompanyBeans) {
                    if (applyCompanyBean.getComNo().equals(relieveBean.getApplyCompanyNo())) {
                        companyId = applyCompanyBean.getId();
                        return;
                    }
                }
            }
        });
        sModel.mDepList.observe(this, companyDeptBeans -> {
            if (companyDeptBeans != null && companyDeptBeans.size() > 0) {
                showDeptPop(companyDeptBeans);
            } else {
                MToast.showToast(MemberRelieveActivity.this, "申请部门暂时为空.");
            }
        });
        sModel.mRelieveSuccess.observe(this, entity -> {
            if ("0".equals(entity.getCode())) {
                // 跳转至页面用户中心-审批列表-我发起的
                romoveSuccess();
            } else {
                MToast.showToast(MemberRelieveActivity.this, entity.getMsg());
            }
        });
        sModel.isSuccessMsg.observe(this, data -> {
            if (data.getState().equals("ok")) {
                romoveSuccess();
            } else {
                MToast.showToast(MemberRelieveActivity.this, data.getMsg());
            }
        });
    }

    private void romoveSuccess() {
        // 跳转至页面用户中心-审批列表-我发起的
        if (flag.equals("1")) {
            // 会员解除申请成功，发送事件通知更新数据
            MToast.showToast(MemberRelieveActivity.this, "会员解除申请成功");
            MemberConfig.getInstance().getInstance().startApprovalManager(MemberRelieveActivity.this, 1);
        } else {
            MToast.showToast(MemberRelieveActivity.this, "解除成功");
        }
        finish();
    }

    @SuppressLint("NonConstantResourceId")
    @Override
    public void OnWholeItemClick(View view) {
        if (view.getId() == R.id.item_input_department) {
            if (sModel.mDepList.getValue() == null || sModel.mDepList.getValue().size() == 0) {
                if (TextUtils.isEmpty(companyId)) {
                    sModel.getMyCompanyList();
                } else {
                    sModel.getDeptList(companyId);
                }
                return;
            }
            showDeptPop(sModel.mDepList.getValue());
        }
    }

    @Override
    public void onMultiClick(View v) {
        if (v.getId() == R.id.submit) {
            String achievement = mBinding.cftPerformance.getEditContent();
            if (TextUtils.isEmpty(achievement)) {
                MToast.showToast(this, "请填写300字以内解除说明");
                return;
            } else
                relieveBean.setReason(achievement);

            if (!getViewList(true)) {
                return;
            }
            relieveBean.setParamDtos(viewList);
            if (flag.equals("1")) {
                MemberCommonDialog dialog = new MemberCommonDialog(new MemberCommonDialog.SimpleListener() {
                    @Override
                    public void onPositive(Object... objects) {
                        sModel.delMember(relieveBean);
                    }
                }, MemberCommonDialog.STYLE_CONFIRM_APPROVAL);
                dialog.show(this, "MemberCommonDialog");
            } else
                sModel.delMember(relieveBean);
        }
    }

    // 选择部门
    public void showDeptPop(List<CompanyDeptBean> mOptionData) {
        if (mOptionDept == null) {
            mOptionDept = new OptionsPickerBuilder(this, (options1, options2, options3, v) -> {
                String name = mOptionData.get(options1).getName();
                String id = mOptionData.get(options1).getId();
                mBinding.itemInputDepartment.getContent_edt().setText(name);
                // 申请部门
                relieveBean.setApplyDeptNo(id);
                relieveBean.setApplyDeptName(name);
            }).setCancelColor(getResources().getColor(R.color.color_title_small)).build();
            mOptionDept.setTitleText("申请部门");
        }
        mOptionDept.setPicker(mOptionData);
        mOptionDept.setSelectOptions(0);
        mOptionDept.show();
    }

    private void addView() {
        if (mBinding.llDescGroup.getChildCount() >= 5) {
            MToast.showToast(getActivity(), "最多设置5个要求");
            return;
        }
        if (!getViewList(false)) {
            return;
        }
        LayoutNewAddItemBinding binding = LayoutNewAddItemBinding.inflate(getLayoutInflater());
        mBinding.llDescGroup.addView(binding.getRoot(), mBinding.llDescGroup.getChildCount());
        binding.ivDel.setOnClickListener(view1 -> {
            mBinding.llDescGroup.removeView(binding.getRoot());
            if (mBinding.tvAddView.getVisibility() != View.VISIBLE) {
                mBinding.tvAddView.setVisibility(View.VISIBLE);
            }
        });
        binding.tvDescContent.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                int n = s.toString().trim().length();
                binding.tvNum.setText(n + "/300");
            }
        });


        if (mBinding.llDescGroup.getChildCount() >= 5) {
            mBinding.tvAddView.setVisibility(View.GONE);
        }

    }

    /**
     * @param isSubmit 是否是提交 是提交 true 是验证 false
     * @return
     */
    public boolean getViewList(boolean isSubmit) {
        if (isSubmit) {
            viewList.clear();
        }
        for (int i = 0; i < mBinding.llDescGroup.getChildCount(); i++) {
            View view = mBinding.llDescGroup.getChildAt(i);
            String title = ((EditText) view.findViewById(R.id.et_title)).getText().toString().trim();
            String content = ((EditText) view.findViewById(R.id.tv_desc_content)).getText().toString().trim();
            if (isSubmit) {
                if (TextUtils.isEmpty(title) && TextUtils.isEmpty(content)) {

                } else {
                    if (TextUtils.isEmpty(title)) {
                        MToast.showToast(getActivity(), "请输入标题");
                        return false;
                    }
                    if (TextUtils.isEmpty(content)) {
                        MToast.showToast(getActivity(), "请输入内容");
                        return false;
                    }
                }
            } else {
                if (TextUtils.isEmpty(title)) {
                    MToast.showToast(getActivity(), "请输入标题");
                    return false;
                }
                if (TextUtils.isEmpty(content)) {
                    MToast.showToast(getActivity(), "请输入内容");
                    return false;
                }
            }

            if (isSubmit) {
                if (!TextUtils.isEmpty(title) && !TextUtils.isEmpty(content)) {
                    MemberRelieveBean.ParamDtos bean = new MemberRelieveBean.ParamDtos();
                    bean.setContent(content);
                    bean.setTitle(title);
                    viewList.add(bean);
                }
            }
        }
        return true;
    }


}